package com.vpen.netty.demo.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/11 22:54
 */
public class AppServer {
    private final Integer port;

    public AppServer(Integer port) {
        this.port = port;
    }

    public void run() {
        NioEventLoopGroup loopGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(loopGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(this.port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HelloWorldServerHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind().sync();
            System.out.println("服务端启动：监听" + future.channel().localAddress());
            // 通道关闭才会执行这句话
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            loopGroup.shutdownGracefully();
        }
    }


    public static void main(String[] args) {
        AppServer appServer = new AppServer(18080);
        appServer.run();
    }
}
